/**
 * Created by YY on 16/8/12.
 */
var _ = require('lodash'),
    Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection');

//查找所有部门
exports.getAllDepartment = function (completeFun) {
    var entity = entityCollection.getEntity("Department");
    entity.find({IsEffective: true}, null, null, function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询部门错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};
//查找部门by _id
exports.findDepartmentById = function (id, completeFun) {
    var entity = entityCollection.getEntity("Department");

    entity.findOne({
        _id: id
    }, null, function (err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询部门信息错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });
};

/**
 * 通过上级部门查询部门
 * @param parentDepartment
 * @param completeFun
 */
exports.getDepartmentByParentDepartment = function (parentDepartment, completeFun) {
    var entity = entityCollection.getEntity("Department");
    entity.find({ParentDepartment: {$in: parentDepartment}, IsEffective: true},
        null,
        [{
            path: 'ParentDepartment',
            select: 'Code Name'
        }], function (err, records) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询部门错误';
                newErr.message = '请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, records);
            }
        });
};

// 查询所有顶级部门
exports.findRootDepartments = function (projection, populate) {
    var deferred = Q.defer();

    projection = projection ? projection : {};

    var entity = entityCollection.getEntity("Department");

    var cursor = entity.Entity.find({ IsEffective: true, ParentDepartment: { $exists: false }}, projection);
    if (populate) {
        cursor = cursor.populate(populate);
    }
    cursor.exec(function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询部门错误';
            newErr.message = '查询部门错误, 请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(records);
    });

    return deferred.promise;
};

// 查询部门下所有子部门
exports.findSubDepartments = function (dpt, projection, populate) {
    var deferred = Q.defer();

    projection = projection ? projection : {};

    var entity = entityCollection.getEntity("Department");

    var cursor = entity.Entity.find({ IsEffective: true, ParentDepartment: dpt }, projection);
    if (populate) {
        cursor = cursor.populate(populate);
    }
    cursor.exec(function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询部门错误';
            newErr.message = '查询部门错误, 请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(records);
    });

    return deferred.promise;
};

// 递归查询部门下所有子部门
exports.findSubDepartmentsDeep = function(dptId) {
    return querySubDepartments([dptId], []);
};

function querySubDepartments(dptIds, resultDptIds) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("Department");
    entity.Entity.find({ IsEffective: true, ParentDepartment: { $in: dptIds } })
    .distinct('_id')
    .exec(function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询部门错误';
            newErr.message = '查询部门错误, 请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        if (records.length === 0) {
            deferred.resolve(resultDptIds);
            return;
        }
        resultDptIds = resultDptIds.concat(records);
        querySubDepartments(records, resultDptIds).then(function (results) {
            deferred.resolve(results);
        }, function (err) {
            deferred.reject(err);
        });
    });

    return deferred.promise;
}
